<?php

namespace Xiaoc\Api;

/**
 * 生成唯一订单号
 * @return string
 */
function get_order_sn()
{
    $time = explode(' ', microtime());
    $time = $time[1] . ($time[0] * 1000);
    $time = explode('.', $time);
    $time = (isset($time[1]) ? $time[1] : 0);
    $time = date('YmdHis') + $time;
    mt_srand((double)microtime() * 1000000);
    return $time . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

/**
 * 数组重新排序
 * @return array
 */
function get_array_sort($arr, $keys, $type = 'asc')
{
    $new_array = array();
    if (is_array($arr) && !empty($arr)) {
        $keysvalue = $new_array = array();

        foreach ($arr as $k => $v) {
            $keysvalue[$k] = $v[$keys];
        }

        if ($type == 'asc') {
            asort($keysvalue);
        } else {
            arsort($keysvalue);
        }

        reset($keysvalue);

        foreach ($keysvalue as $k => $v) {
            $new_array[$k] = $arr[$k];
        }
    }

    return $new_array;
}

/**
 * 获取两个经纬度之间的距离
 * @param $lat1
 * @param $lng1
 * @param $lat2
 * @param $lng2
 * @return int
 */
/* 获取两个金纬度之间的距离 */
function distanceByLnglat($lng1, $lat1, $lng2, $lat2)
{
    $earthRadius = 6367000; //approximate radius of earth in meters
    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;
    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return $calculatedDistance;
}

function Rad($d)
{
    return $d * M_PI / 180.0;
}

//处理sql
function db_create_in($item_list, $field_name = '')
{
    if (empty($item_list)) {
        return $field_name . ' IN (\'\') ';
    } else {
        if (!is_array($item_list)) {
            $item_list = explode(',', $item_list);
        }

        $item_list = array_unique($item_list);
        $item_list_tmp = '';

        foreach ($item_list as $item) {
            if ($item !== '') {
                $item = addslashes($item);
                $item_list_tmp .= ($item_list_tmp ? ',\'' . $item . '\'' : '\'' . $item . '\'');
            }
        }

        if (empty($item_list_tmp)) {
            return $field_name . ' IN (\'\') ';
        } else {
            return $field_name . ' IN (' . $item_list_tmp . ') ';
        }
    }
}

/**
 * 获取输入参数 支持过滤和默认值
 * @param string $name 变量的名称 支持指定类型
 * @param mixed $default 不存在的时候默认值
 * @param mixed $filter 参数过滤方法
 * @param mixed $datas 要获取的额外数据源
 * @return mixed
 */
function ApiGet($name, $default = '', $filter = null, $datas = null)
{
    if (strpos($name, '/')) { // 指定修饰符
        list($name, $type) = explode('/', $name, 2);
    }
    if (strpos($name, '.')) { // 指定参数来源
        list($method, $name) = explode('.', $name, 2);
    } else { // 默认为自动判断
        $method = 'param';
    }
    switch (strtolower($method)) {
        case 'get' :
            $input = &$_GET;
            break;
        case 'post' :
            $input = &$_POST;
            break;
        case 'put' :
            parse_str(file_get_contents('php://input'), $input);
            break;
        case 'param' :
            switch ($_SERVER['REQUEST_METHOD']) {
                case 'POST':
                    $input = $_POST;
                    break;
                case 'PUT':
                    parse_str(file_get_contents('php://input'), $input);
                    break;
                default:
                    $input = $_GET;
            }
            break;
        case 'path' :
            $input = array();
            if (!empty($_SERVER['PATH_INFO'])) {
                $depr = C('URL_PATHINFO_DEPR');
                $input = explode($depr, trim($_SERVER['PATH_INFO'], $depr));
            }
            break;
        case 'request' :
            $input = &$_REQUEST;
            break;
        case 'session' :
            $input = &$_SESSION;
            break;
        case 'cookie' :
            $input = &$_COOKIE;
            break;
        case 'server' :
            $input = &$_SERVER;
            break;
        case 'globals' :
            $input = &$GLOBALS;
            break;
        case 'data' :
            $input = &$datas;
            break;
        default:
            return NULL;
    }
    if ('' == $name) { // 获取全部变量
        $data = $input;
        $filters = isset($filter) ? $filter : '';
        if ($filters) {
            if (is_string($filters)) {
                $filters = explode(',', $filters);
            }
            foreach ($filters as $filter) {
                $data = array_map_recursive($filter, $data); // 参数过滤
            }
        }
    } elseif (isset($input[$name])) { // 取值操作
        $data = $input[$name];
        $filters = isset($filter) ? $filter : '';
        if ($filters) {
            if (is_string($filters)) {
                $filters = explode(',', $filters);
            } elseif (is_int($filters)) {
                $filters = array($filters);
            }

            foreach ($filters as $filter) {
                if (function_exists($filter)) {
                    $data = is_array($data) ? array_map_recursive($filter, $data) : $filter($data); // 参数过滤
                } elseif (0 === strpos($filter, '')) {
                    // 支持正则验证
                    if (1 !== preg_match($filter, (string)$data)) {
                        return isset($default) ? $default : NULL;
                    }
                } else {
                    $data = filter_var($data, is_int($filter) ? $filter : filter_id($filter));
                    if (false === $data) {
                        return isset($default) ? $default : NULL;
                    }
                }
            }
        }
        if (!empty($type)) {
            switch (strtolower($type)) {
                case 's':   // 字符串
                    $data = (string)$data;
                    break;
                case 'a': // 数组
                    $data = (array)$data;
                    break;
                case 'd': // 数字
                    $data = (int)$data;
                    break;
                case 'f': // 浮点
                    $data = (float)$data;
                    break;
                case 'b': // 布尔
                    $data = (boolean)$data;
                    break;
            }
        }
    } else { // 变量默认值
        $data = isset($default) ? $default : NULL;
    }
    is_array($data) && array_walk_recursive($data, 'Xiaoc_filter');
    return $data;
}

function array_map_recursive($filter, $data)
{
    $result = array();
    foreach ($data as $key => $val) {
        $result[$key] = is_array($val) ? array_map_recursive($filter, $val) : call_user_func($filter, $val);
    }
    return $result;
}

/**
 * Name: 过滤查询特殊字符
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $value
 */
function Xiaoc_filter(&$value)
{
    if (preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i', $value)) {
        $value .= ' ';
    }
}

/**
 * 浏览器友好的变量输出
 * @param mixed $var 变量
 * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 * @param string $label 标签 默认为空
 * @param boolean $strict 是否严谨 默认为true
 * @return void|string
 */
function dump($var, $echo = true, $label = null, $strict = true)
{
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    } else
        return $output;
}

function halt($var, $echo = true, $label = null, $strict = true)
{
    dump($var, $echo, $label, $strict);
    exit();
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function getIp($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos)
            unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 检查是否是微信浏览器访问
 */
function is_wechat_browser()
{
    $user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (strpos($user_agent, 'micromessenger') === false) {
        return false;
    } else {
        return true;
    }
}

/**
 * 二维数组排序
 * @param array $array 排序的数组
 * @param string $key 排序主键
 * @param string $type 排序类型 asc|desc
 * @param bool $reset 是否返回原始主键
 * @return array
 */
function array_order($array, $key, $type = 'asc', $reset = false)
{
    if (empty($array) || !is_array($array)) {
        return $array;
    }
    foreach ($array as $k => $v) {
        $keysvalue[$k] = $v[$key];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    $i = 0;
    foreach ($keysvalue as $k => $v) {
        $i++;
        if ($reset) {
            $new_array[$k] = $array[$k];
        } else {
            $new_array[$i] = $array[$k];
        }
    }
    return $new_array;
}

/**
 * 中英文字符串截取
 * @param  string $str 字符串
 * @param  integer $start 起始长度
 * @param  integer $length 截取长度
 * @param  string $charset 字符编码
 * @param  boolean $suffix 截取后缀
 * @return string
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    if ($charset != 'utf-8') {
        $str = mb_convert_encoding($str, 'utf8', $charset);
    }
    $osLen = mb_strlen($str);
    if ($osLen <= $length) {
        return $str;
    }
    $string = mb_substr($str, $start, $length, 'utf8');
    $sLen = mb_strlen($string, 'utf8');
    $bLen = strlen($string);
    $sCharCount = (3 * $sLen - $bLen) / 2;
    if ($osLen <= $sCharCount + $length) {
        $arr = preg_split('/(?<!^)(?!$)/u', mb_substr($str, $length + 1, $osLen, 'utf8')); //将中英混合字符串分割成数组（UTF8下有效）
    } else {
        $arr = preg_split('/(?<!^)(?!$)/u', mb_substr($str, $length + 1, $sCharCount, 'utf8'));
    }
    foreach ($arr as $value) {
        if (ord($value) < 128 && ord($value) > 0) {
            $sCharCount = $sCharCount - 1;
        } else {
            $sCharCount = $sCharCount - 2;
        }
        if ($sCharCount <= 0) {
            break;
        }
        $string .= $value;
    }
    return $string;
    if ($suffix)
        return $string . "…";
    return $string;
}

/**
 * 字符串转码
 * @param  string $fContents 字符串
 * @param  string $from 原始编码
 * @param  string $to 目标编码
 * @return string
 */
function auto_charset($fContents, $from = 'gbk', $to = 'utf-8')
{
    $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
    $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
    if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
        //如果编码相同或者非字符串标量则不转换
        return $fContents;
    }
    if (is_string($fContents)) {
        if (function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($fContents, $to, $from);
        } elseif (function_exists('iconv')) {
            return iconv($from, $to, $fContents);
        } else {
            return $fContents;
        }
    } elseif (is_array($fContents)) {
        foreach ($fContents as $key => $val) {
            $_key = $this->auto_charset($key, $from, $to);
            $fContents[$_key] = $this->auto_charset($val, $from, $to);
            if ($key != $_key)
                unset($fContents[$key]);
        }
        return $fContents;
    } else {
        return $fContents;
    }
}

/**
 * 加密函数
 * @param  mixed $data 加密数据
 * @param  string $key 密匙
 * @param  integer $expire 失效时间
 * @return string
 */
function cpEncode($data, $key = '', $expire = 0)
{
    $string = serialize($data);
    $ckey_length = 4;
    if (empty($key)) {
        $sys = \PhalApi\DI()->config->get('sys');
        $key = $sys['crypt']['mcrypt_iv'];
    }
    $key = md5($key);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = substr(md5(microtime()), -$ckey_length);

    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string = sprintf('%010d', $expire ? $expire + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    return $keyc . str_replace('=', '', base64_encode($result));
}

/**
 * 解密函数
 * @param  string $string 加密字符串
 * @param  string $key 密匙
 * @return mixed
 */
function cpDecode($string, $key = '')
{
    $ckey_length = 4;
    if (empty($key)) {
        $sys = \PhalApi\DI()->config->get('sys');
        $key = $sys['crypt']['mcrypt_iv'];
    }
    $key = md5($key);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = substr($string, 0, $ckey_length);

    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string = base64_decode(substr($string, $ckey_length));
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
        return unserialize(substr($result, 26));
    } else {
        return '';
    }
}

/**
 * HTML代码过滤
 * @param  string $str 字符串
 * @return string
 */
function escapeHtml($str)
{
    $search = array("'<script[^>]*?>.*?</script>'si", // 去掉 javascript
        "'<iframe[^>]*?>.*?</iframe>'si", // 去掉iframe
    );
    $replace = array("",
        "",
    );
    $str = preg_replace($search, $replace, $str);
    $str = htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
    return $str;
}

/**
 * Name: 判断邮箱
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $email
 * @return bool
 */
function isEmail($email)
{
    $mode = "/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i";
    if (preg_match($mode, $email)) {
        return true;
    } else {
        return false;
    }
}

/**
 * Name:判断是不是手机
 * User: wanghousheng
 * Date: 2017/6/15
 * @param $mobile
 * @return bool
 */
function isMobile($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('/^1[34578]{1}\d{9}$/', $mobile) ? true : false;
}

/**
 * Name: 验证身份证
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $field
 * @param int $type
 * @return mixed
 */
function isCreditNo($id_card)
{
    if (strlen($id_card) == 18) {
        return idcard_checksum18($id_card);
    } elseif ((strlen($id_card) == 15)) {
        $id_card = idcard_15to18($id_card);
        return idcard_checksum18($id_card);
    } else {
        return false;
    }
}

// 计算身份证校验码，根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base)
{
    if (strlen($idcard_base) != 17) {
        return false;
    }
    //加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    //校验码对应值
    $verify_number_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    $checksum = 0;
    for ($i = 0; $i < strlen($idcard_base); $i++) {
        $checksum += substr($idcard_base, $i, 1) * $factor[$i];
    }
    $mod = $checksum % 11;
    $verify_number = $verify_number_list[$mod];
    return $verify_number;
}

// 将15位身份证升级到18位
function idcard_15to18($idcard)
{
    if (strlen($idcard) != 15) {
        return false;
    } else {
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if (array_search(substr($idcard, 12, 3), array('996', '997', '998', '999')) !== false) {
            $idcard = substr($idcard, 0, 6) . '18' . substr($idcard, 6, 9);
        } else {
            $idcard = substr($idcard, 0, 6) . '19' . substr($idcard, 6, 9);
        }
    }
    $idcard = $idcard . idcard_verify_number($idcard);
    return $idcard;
}

// 18位身份证校验码有效性检查
function idcard_checksum18($idcard)
{
    if (strlen($idcard) != 18) {
        return false;
    }
    $idcard_base = substr($idcard, 0, 17);
    if (idcard_verify_number($idcard_base) != strtoupper(substr($idcard, 17, 1))) {
        return false;
    } else {
        return true;
    }
}

/**
 * Name: 生成图形验证码
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $str
 * @param array $config
 * @return bool|void
 */
function MakeCode($str, $config = array())
{
    if ($str) {
        $verify = new \Verify_Lite($config);
        return $verify->entry($str);
    }
    return false;
}

/**
 * Name: 检查图形验证码是否正确
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $str
 * @param $code
 */
function CheckCode($str, $code)
{
    if ($str && $code) {
        $verify = new \Verify_Lite();
        return $verify->check($code, $str);
    }
    return false;
}

/**
 * Name: 创蓝短信接口
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $config
 * @param $mobile
 * @param string $code
 */
function send_code($mobile, $type = 4, $code = '')
{
    if (isMobile($mobile)) {
        $di = \PhalApi\DI();
        $where['code'] = array('chuanglan_u', 'chuanglan_p');
        $config = $di->medoo->select('shop_config', array('value'), $where);
        var_export($di);
        die;
        $data['sign'] = "【校创科技】"; //签名
        $data['time'] = 60; //短信频率
        $data['username'] = 'xckj2017';
        $data['password'] = '123456';
        $sms = new \Sms_Lite($data);
        return $sms->send_code($mobile, $type, $code);
    }
}

/**
 * Name: 方法名称
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $mobile
 * @param $code
 * @return bool
 */
function check_code($mobile, $code)
{
    /*if (isMobile($mobile) && $code) {
        $di = \PhalApi\DI();
        $where['code'] = array('chuanglan_u', 'chuanglan_p');
        $config = $di->medoo->select('shop_config', array('value'), $where);
        if ($config) {
            $data['time'] = 60; //短信频率
            $data['username'] = $config[0]['value'];
            $data['password'] = $config[1]['value'];
            $sms = new \Sms_Lite($data);
            $res_code = $sms->check_code($mobile, $code);
            if ($res_code) {
                return true;
            }
        }
    }*/
    $sms = new \Sms_Lite();
    $res_code = $sms->check_code($mobile, $code);
    if ($res_code) {
        return true;
    }
    return false;
}

/**
 * 价格格式化
 *
 * @param int $price
 * @return string    $price_format
 */
function ncPriceFormat($price)
{
    return number_format($price, 2, '.', '');
}

/**
 * Name: 验证银行卡是不正确 聚合数据
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $number
 * @return bool
 */
function CheckBank($number)
{
    if (is_numeric($number)) {
        $key = '';
        $url = 'http://detectionBankCard.api.juhe.cn/bankCard?cardid=' . $number . '&key=' . $key;
        $result = getUrl($url);
        $result = json_decode($result, true);
        if (!$result['error_code']) {
            $arr['bank'] = $result['result']['bank'];
            $arr['nature'] = $result['result']['nature'];
            return $arr;
        }
    }
    return false;
}

/**
 * Name: curl get
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $url
 * @return mixed
 */
function getUrl($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    if (!empty($options)) {
        curl_setopt_array($ch, $options);
    }
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

function getImage($url, $save_dir = '../img/images_user/', $filename = '')
{
    if (empty($filename)) {
        $filename = sprintf('%010d', time() - 946656000) . sprintf('%04d', mt_rand(0, 9999)) . 'jpg';
    }

    if (0 !== strrpos($save_dir, '/')) {
        $save_dir .= '/';
    }
    //获取远程文件所采用的方法
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $img = curl_exec($ch);
    curl_close($ch);
    //$size=strlen($img);
    //文件大小
    $fp2 = @fopen($save_dir . $filename, 'a');
    fwrite($fp2, $img);
    fclose($fp2);
    unset($img, $url);
    return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
}


function gmtime()
{
    return time();
//    return time() - date('Z');
}

/**
 * Name: 时间格式化
 * User: wanghousheng
 * Date: 2017/6/15
 * @param null $time
 * @param string $format
 * @return false|string
 */
function time_format($time = NULL, $format = 'Y-m-d H:i:s')
{
    $timezone = 8;

    if ($time === NULL) {
        $time = gmtime();
    } else if ($time <= 0) {
        return '';
    }

    $time += $timezone * 3600;
    return date($format, $time);
}

/**
 * Name: ftp上传图片
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $rootPath
 */
function ftp_uplaod($save)
{
    $di = \PhalApi\DI();
    $app_config = $di->config->get('app');
    $ftpConfig = $app_config['ftp_upload'];
    return new \UCloud_Lite($ftpConfig, 'Ftp', $save);
}

/**
 * 获取校园汇优品
 * @param  [type] $where 查询条件
 * @param  [type] $order 查询排序
 * @param  [type] $limit 查询数量
 * @return [type]        返回结果
 */
function getLists($where, $order, $limit)
{
    $prefix = \PhalApi\DI()->config->get('dbs.tables.__default__.prefix');
    $sql = 'SELECT a.goods_id,a.goods_name,a.shop_price,a.market_price,a.goods_thumb FROM ' . $prefix . 'goods as a JOIN ' . $prefix . 'merchants_shop_information as b ON a.user_id=b.user_id  WHERE ' . $where . ' order by ' . $order . ' limit ' . $limit;
    $res = \PhalApi\DI()->notorm->goods->queryRows($sql, array());
    foreach ($res as $k => $v) {
        $img = explode(',', $v['goods_thumb']);
        $v['goods_thumb'] = $img[0];
        $res[$k] = $v;
    }
    return $res;
}

/**
 * 获取校园汇众筹
 * @param  [type] $where 查询条件
 * @param  [type] $order 查询排序
 * @param  [type] $limit 查询数量
 * @return [type]        返回结果
 */
function getCrowdLists($where, $order, $limit)
{
    $prefix = \PhalApi\DI()->config->get('dbs.tables.__default__.prefix');
    $sql = 'SELECT b.goods_id,b.goods_name,b.shop_price,b.market_price,b.goods_thumb,a.act_id FROM ' . $prefix . 'goods_activity as a JOIN ' . $prefix . 'goods as b ON a.goods_id=b.goods_id  WHERE ' . $where . ' order by ' . $order . ' limit ' . $limit;
    $res = \PhalApi\DI()->notorm->goods_activity->queryRows($sql, array());
    foreach ($res as $k => $v) {
        $img = explode(',', $v['goods_thumb']);
        $v['goods_thumb'] = $img[0];
        $res[$k] = $v;
    }
    return $res;
}

/**
 * 获取盒子列表
 * @param  [type] $where 查询条件
 * @param  [type] $order 查询排序
 * @param  [type] $limit 查询数量
 * @return [type]        返回结果
 */
function getBoxLists($where, $order, $limit)
{
    $res = \PhalApi\DI()
        ->notorm
        ->goods
        ->select('goods_id,goods_name,shop_price,market_price,goods_thumb')
        ->where($where)
        ->order($order)
        ->limit(0, $limit);
    foreach ($res as $k => $v) {
        $img = explode(',', $v['goods_thumb']);
        $v['goods_thumb'] = $img[0];
        $res[$k] = $v;
    }
    return $res;
}

/**
 * Name:获取表前缀
 * User: wanghousheng
 * Date: 2016/12/27
 */
function get_table_prefix()
{
    $config = \PhalApi\DI()->config->get('dbs');
    return $config['tables']['__default__']['prefix'];
}


/**
 * 获取广告信息
 * @param  [type] $where 查询条件
 * @return [type]        返回结果
 */
function getAdsInfo($where)
{
    $res = \PhalApi\DI()
        ->notorm
        ->ad
        ->select('*')
        ->where($where)
        ->fetchOne();
    return $res;
}


/**
 * 获取商品信息
 * @param  [type] $where 查询条件
 * @return [type]        返回结果
 */
function getGoodsInfo($where)
{
    $res = \PhalApi\DI()
        ->notorm
        ->goods
        ->select('*')
        ->where($where)
        ->fetchOne();
    return $res;
}

/**
 * Name:截取字符串使其中间变为*号
 * User: wanghousheng
 * Date: 2016/12/27
 * @param $str
 * @param $start
 * @param int $end
 * @param string $dot
 * @param string $charset
 * @return string
 */
/*function PassStart($str,$start,$end=0,$dot="****",$charset="UTF-8"){
	$str = trim($str);
    $len = mb_strlen($str,$charset);
    if($start==0||$start>$len){
        $start = 1;
    }
    if($end!=0&&$end>$len){
        $end = $len-2;
    }
    $endStart = $len-$end;
    $top = mb_substr($str, 0,$start,$charset);
    $bottom = "";
    if($endStart>0){
        $bottom =  mb_substr($str, $endStart,$end,$charset);
    }
    $newStr = $top;
    $newStr.=$dot;
    $newStr.=$bottom;
    return $newStr;
}*/
function PassStart($str, $start, $end = 0, $dot = "****", $charset = "UTF-8")
{
    $str = trim($str);
    $len = mb_strlen($str, $charset);
    $count = mb_strlen($dot, $charset) + $start + $end;
    if ($len < $count) {
        if ($len > 2) {
            $front = mb_substr($str, 0, 1, $charset);
            $after = mb_substr($str, -1, $charset);
        } else {
            return $str;
        }
    } else {
        $front = mb_substr($str, 0, $start, $charset);
        $after = mb_substr($str, 0 - $end, null, $charset);
    }
    return $front . $dot . $after;
}

/**
 * 获得可用的会员名
 * @param string $prefix
 * @param int $num
 * @return string
 */
function getMemberName($prefix = 'user_', $num = 0)
{
    if ($num < 1) {
        $num = rand(100, 899);
    }
    if (strlen($prefix) < 3) {
        $member_name = $prefix . $num;
    } else {
        $member_name = $prefix;
    }
    if (strlen($member_name) < 6) {
        $member_name = $member_name . $num;
    }
    $member = \PhalApi\DI()->medoo->get('users', 'user_name', array('user_name' => $member_name));
    if (!empty($member)) {
        for ($i = 1; $i < 999; $i++) {
            $num += $i;
            $member_name = $prefix . $num;
            if (strlen($member_name) < 6) {
                $member_name = 'user_' . $member_name;
            }
            $member = \PhalApi\DI()->medoo->get('users', 'user_name', array('user_name' => $member_name));
            if (empty($member)) {
                break;
            }
        }
    }
    return $member_name;
}

function get_time_shaft($time)
{
    if (empty($time)) $time = time();
    $time = time() - $time;
    if ($time < 60) {
        $str = '刚刚';
    } elseif ($time < 60 * 60) {
        $min = floor($time / 60);
        $str = $min . '分钟前';
    } elseif ($time < 60 * 60 * 24) {
        $h = floor($time / (60 * 60));
        $str = $h . '小时前';
    } elseif ($time < 60 * 60 * 24 * 3) {
        $d = floor($time / (60 * 60 * 24));
        if ($d == 1)
            $str = '昨天';
        else
            $str = '前天';
    } elseif ($time < 60 * 60 * 24 * 7) {
        $str = '一周前';
    } else {
        $str = date('Y-m-d', $time);
    }
    return $str;
}

/**
 * 获取等级名
 * @param $user_rank
 * @return 返回等级名
 */
function rankNames($user_rank)
{
    /*$rank_name = \PhalApi\DI()->notorm
        ->user_rank
        ->select('rank_name')
        ->where(array('min_points <= ?' => $rank_points, 'max_points >= ?' => $rank_points))
        ->fetchRow();*/
    $rank_name = \PhalApi\DI()->notorm
        ->user_rank
        ->select('rank_name')
        ->where(array('rank_id' => $user_rank))
        ->fetchRow();
    return $rank_name['rank_name'];
}

/**
 * 根据等级查询会员
 * @param $user_id int 会员id
 * @param $level int 查询的会员等级(如:1级会员)
 * @return mixed 会员
 */
function getMembersByLevel($user_id, $level)
{
    switch ($level) {
        case 1:
            $users = \PhalApi\DI()->notorm
                ->users
                ->select('user_id')
                ->where(array('parent_id' => $user_id));
            break;
        case 2:
            $sql = 'Select user_id from dsc_users WHERE parent_id IN (SELECT user_id FROM dsc_users WHERE parent_id = ' . $user_id . ')';
            $users = \PhalApi\DI()->notorm
                ->users
                ->queryAll($sql, array());
            break;
        case 3:
            $sql = 'select user_id FROM  dsc_users WHERE parent_id IN (Select user_id from dsc_users WHERE parent_id IN (SELECT user_id FROM dsc_users WHERE parent_id = ' . $user_id . '))';
            $users = \PhalApi\DI()->notorm
                ->users
                ->queryAll($sql, array());
            break;
    }
    return $users;
}

/**
 * @return array 获取秒杀时间duan
 */
function get_seckill_time()
{
    $prefix = \PhalApi\DI()->config->get('dbs.tables.__default__.prefix');
    $now = gmtime();
    $day = 24 * 60 * 60 * 7;
    $date_begin = strtotime(date('Y-m-d'));
    $date_next = strtotime(date('Y-m-d')) + $day;
    $sql = 'SELECT id,title, begin_time, end_time FROM ' . $prefix . 'seckill_time_bucket ORDER BY begin_time ASC ';
    $stb = \PhalApi\DI()->notorm->seckill_time_bucket->queryAll($sql, array());
    $arr = array();
    if ($stb) {
        foreach ($stb as $k => $v) {
            $v['local_end_time'] = strtotime($v['end_time']);
            if ($now < $v['local_end_time']) {
                $arr[$k]['id'] = $v['id'];
                $arr[$k]['title'] = $v['title'];
                $arr[$k]['status'] = false;
                $arr[$k]['is_end'] = false;
                $arr[$k]['soon'] = true;
                $arr[$k]['begin_time'] = $begin_time = strtotime($v['begin_time']);
                $arr[$k]['end_time'] = $end_time = strtotime($v['end_time']);
                $arr[$k]['frist_end_time'] = date('Y-m-d H:i:s', strtotime($v['end_time']));
                if (($begin_time < $now) && ($now < $end_time)) {
                    $arr[$k]['status'] = true;
                }

                if ($end_time < $now) {
                    $arr[$k]['is_end'] = true;
                }

                if ($now < $begin_time) {
                    $arr[$k]['soon'] = true;
                }
            }
        }

        //如果时间段大于4个,从数组中取出四个值
        if (4 < count($arr)) {
            $arr = array_slice($arr, 0, 4);
        }
        //如果时间段小于4个
        if (count($arr) < 4) {
            //如果数组中的count为0,从数组中取出四个值
            if (count($arr) == 0) {
                $stb = array_slice($stb, 0, 4);
            }
            //如果数组中的count为1,从数组中取出三个值
            if (count($arr) == 1) {
                $stb = array_slice($stb, 0, 3);
            }
            //如果数组中的count为2,从数组中取出两个值
            if (count($arr) == 2) {
                $stb = array_slice($stb, 0, 2);
            }
            //如果数组中的count为3,从数组中取出一个值
            if (count($arr) == 3) {
                $stb = array_slice($stb, 0, 1);
            }

            foreach ($stb as $k => $v) {
                $arr['tmr' . $k]['id'] = $v['id'];
                $arr['tmr' . $k]['title'] = $v['title'];
                $arr['tmr' . $k]['status'] = false;
                $arr['tmr' . $k]['is_end'] = false;
                $arr['tmr' . $k]['soon'] = true;
                $arr['tmr' . $k]['begin_time'] = strtotime($v['begin_time']) + $day;
                $arr['tmr' . $k]['end_time'] = strtotime($v['end_time']) + $day;
                $arr['tmr' . $k]['frist_end_time'] = date('Y-m-d H:i:s', strtotime($v['end_time']) + $day);
                $arr['tmr' . $k]['tomorrow'] = 1;
            }
        }
    }

    return $arr;
}

/**
 * 秒杀状态
 * @param $begin_time
 * @param $end_time
 * @return array
 */
function seckill_status($begin_time, $end_time)
{
    $now = gmtime();
    $arr = array();
    $arr['status'] = false;
    $arr['is_end'] = false;
    $arr['soon'] = false;
    if (($begin_time < $now) && ($now < $end_time)) {
        $arr['status'] = true;
    }

    if ($end_time < $now) {
        $arr['is_end'] = true;
    }

    if ($now < $end_time) {
        $arr['soon'] = true;
    }

    return $arr;
}

/**
 * @param string $id
 * @param int $page
 * @param int $offset
 * @param $tomorrow
 * @return array
 */
function seckill_goods_results($id = '', $page = 1, $offset = 5, $tomorrow)
{
    $prefix = \PhalApi\DI()->config->get('dbs.tables.__default__.prefix');
    $date_begin = strtotime(date('Ymd'));
    $sql = 'SELECT GROUP_CONCAT(s2.sec_id) AS sec_id FROM ' . $prefix . 'seckill as s2 WHERE s2.begin_time <= ' . $date_begin . '  AND s2.acti_time >= ' . $date_begin . ' ORDER BY s2.acti_time ASC LIMIT 1';
    $seckill = \PhalApi\DI()->notorm->seckill->queryRows($sql, array());
    $where = '';
    if ($seckill[0]['sec_id']) {
        $where .= ' AND s.sec_id IN(' . $seckill['sec_id'] . ')';
    } else {
        $where .= ' AND s.sec_id IN(0)';
    }

    $offset = 5;
    $limit = ' limit ' . (($page - 1) * $offset) . ',' . $offset;
    $sql = ' SELECT g.goods_id, g.goods_thumb, g.shop_price, g.market_price, g.goods_name, sg.id, sg.sec_price, sg.sec_num, sg.sec_limit, stb.begin_time, stb.end_time, s.sec_id, s.acti_title, s.acti_time FROM ' . $prefix . 'seckill_goods AS sg LEFT JOIN ' . $prefix . 'seckill_time_bucket AS stb ON sg . tb_id = stb . id  LEFT JOIN ' . $prefix . 'seckill AS s ON s.sec_id = sg.sec_id  LEFT JOIN ' . $prefix . 'goods AS g ON sg.goods_id = g.goods_id  WHERE s.is_putaway = 1 AND s . begin_time <= \'' . $date_begin . '\' AND stb.id = \'' . $id . '\' ' . $where . ' ORDER BY stb.begin_time ASC ';
    $counts = \PhalApi\DI()->notorm->seckill_goods->queryAll($sql, array());
    $counts = (is_array($counts) ? count($counts) : 0);
    $sql = ' SELECT g.goods_id, g.goods_thumb, g.shop_price, g.market_price, g.goods_name, sg.id, sg.sec_price, sg.sec_num, sg.sec_limit, stb.begin_time, stb.end_time, s.sec_id, s.acti_title, s.acti_time FROM ' . $prefix . 'seckill_goods AS sg LEFT JOIN ' . $prefix . 'seckill_time_bucket AS stb ON sg.tb_id = stb.id ' . ' LEFT JOIN ' . $prefix . 'seckill AS s ON s.sec_id = sg.sec_id ' . ' LEFT JOIN ' . $prefix . 'goods AS g ON sg.goods_id = g.goods_id  WHERE s.is_putaway = 1 AND s.begin_time <= \'' . $date_begin . '\' AND stb.id = \'' . $id . '\' ' . $where . ' ORDER BY stb.begin_time ASC ' . $limit;
    $res = \PhalApi\DI()->notorm->seckill_goods->queryAll($sql, array());
    $now = gmtime();
    $tmr = 86400;

    if ($res) {
        foreach ($res as $k => $v) {
            if ($tomorrow == 1) {
                $res[$k]['begin_time'] = strtotime($v['begin_time']) + $tmr;
                $res[$k]['end_time'] = strtotime($v['end_time']) + $tmr;
            } else {
                $res[$k]['begin_time'] = strtotime($v['begin_time']);
                $res[$k]['end_time'] = strtotime($v['end_time']);
            }

            if (($res[$k]['begin_time'] < $now) && ($now < $res[$k]['end_time'])) {
                $res[$k]['status'] = true;
            }

            if ($res[$k]['end_time'] < $now) {
                $res[$k]['is_end'] = true;
            }

            if ($now < $res[$k]['begin_time']) {
                $res[$k]['soon'] = true;
            }

            $res[$k]['data_end_time'] = date('H:i:s', $res[$k]['begin_time']);
            $res[$k]['sec_price_formated'] = price_format($v['sec_price']);
            $res[$k]['market_price_formated'] = price_format($v['market_price']);
            $res[$k]['sales_volume'] = sec_goods_stats($v['id']);
            $res[$k]['valid_goods'] = $res[$k]['sales_volume']['valid_goods'];
            $res[$k]['percent'] = ceil(($res[$k]['sales_volume']['valid_goods'] / ($v['sec_num'] + $res[$k]['sales_volume']['valid_goods'])) * 100);
            $res[$k]['goods_thumb'] = get_image_path($v['goods_thumb']);
            $res[$k]['url'] = url('seckill/index/detail', array('id' => $v[id], 'tmr' => $tomorrow));
        }
    }

    $result = array('list' => $res, 'totalPage' => ceil($counts / $offset));
    return $result;
}